import React, { useEffect, useMemo, useState } from "react";
import { Input, Space, Button } from "antd";
import XlTimeRangeModal from "./XlTimeRangeModal";

type formItemProps = {
  value?: any,
  onChange?: any
}

const XlTimeRange = ({value, onChange}: formItemProps) => {
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState<any>({
    date: '',
    time: ''
  });

  const addressProps = {
    visible,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: (res: any) => {
      addressProps.onCancel();
      setCurrent(res);
      onChange(res);
    }
  }

  useEffect(() => {
    if (value) {
      setCurrent({
        date: value?.date,
        time: value?.time
      });
    } else {
      setCurrent({
        date: '',
        time: ''
      });
    }
  }, [JSON.stringify(value)])

  const title = useMemo(() => {
    if (!current) {
      return ''
    }
    return `${current?.date} ${current?.time}`
  }, [JSON.stringify(current)]);

  return (
    <>
      <Space>
        <Input value={title} readOnly style={{width: 250}} />
        <Button type="primary" onClick={() => setVisible(true)}>选择时间</Button>
      </Space>
      {visible && <XlTimeRangeModal {...addressProps} />}
    </>
  );
}
export default XlTimeRange;